﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
 
namespace ProgNetComponentsDx.Components
{
    public class FileBgAppender : BaseBgAppender
    {
        private string _FileName;
        private FileStream _FileStream = null;
        private StreamWriter _Writter = null;
        public string FileName
        {
            get { return _FileName; }
            set
            {
                CloseStreams();
                _FileName = value;
            }
        }
        public override void Start()
        {
            EnsureStreams();
            base.Start();
        }
        private void EnsureStreams()
        {
            if (_FileStream == null)
            {
                _FileStream = File.Open(FileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                _Writter = new StreamWriter(_FileStream);
            }
        }
        private void CloseStreams()
        {
            if (_FileStream != null)
            {
                try { _Writter.Close(); }
                catch (Exception ex) { ex.LogInternal("Error closing Writter"); }

                try { _Writter.Dispose(); }
                catch (Exception ex) { ex.LogInternal("Error disposing Writter"); }

                try { _FileStream.Close(); }
                catch (Exception ex) { ex.LogInternal("Error closing FileStream"); }

                try { _FileStream.Dispose(); }
                catch (Exception ex) { ex.LogInternal("Error disposing FileStream"); }

                _FileStream = null;
                _Writter = null;
            }
            
        }
        public override void Finish()
        {
            base.Finish();
            CloseStreams();
        }
        protected override void AppendFullLines(string fullLines)
        {
            if (FileName.IsNotNull())
            {
                EnsureStreams();
                try
                {
                    _Writter.WriteLine(fullLines);
                    _Writter.Flush();
                }
                catch { }
            }
        }
    }
}
